package com.oa.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.common.utils.*;
import com.oa.modules.sys.entity.SysDeptEntity;
import com.oa.modules.sys.entity.SysUserEntity;
import com.oa.modules.sys.service.SysDeptService;
import com.oa.modules.sys.service.SysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 部门表
 *
 * @author sunhui
 * @email 707022627@qq.com
 * @date 2019-10-10 18:23:00
 */
@RestController
@Api(tags = "部门相关接口")
@RequestMapping("generator/sysdept")
public class SysDeptController extends AbstractController {
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 列表
     */
    @PostMapping("/list")
    @ApiOperation(value = "列表")
    @RequiresPermissions("generator:sysdept:list")
    public R list(@RequestBody Map<String,Object> map) {
        //if (StringUtils.isNotBlank(sysDeptEntity.getTenantId())) {
        //    params.put("tenantId", sysDeptEntity.getTenantId());
        //} else {
        //    params.put("tenantId", getTenantId());
        //}
        //map.put("name", map.get("dept_name"));
        PageUtils page = sysDeptService.queryPage(map);
        List<SysDeptEntity> list = (List<SysDeptEntity>) page.getList();
        list.forEach(data -> {
            data.setUser(sysUserService.getById(data.getCreateBy()));
            data.setLeaderUser(sysUserService.getById(data.getLeader()));
        });
        Collections.sort(list);
        Map result = PageUtils.startListPage(list,1,Integer.valueOf(map.get("top").toString()));
        List<SysDeptEntity> topList = castList(result.get("list"), SysDeptEntity.class); //根据部门实体类中的orderSize字段进行排序。
        page.setList(topList);
        return R.ok().put("page", page);
    }

    /**
     * list 排序
     * @param obj
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> castList(Object obj, Class<T> clazz)
    {
        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>)
        {
            for (Object o : (List<?>) obj)
            {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }


    /**
     * 查询商铺下的订单数量
     *
     * @参数   deptId
     * @return
     */
    @PostMapping("/qryShopView")
    @ApiOperation(value = "查询商铺下的订单数量")
    public R qryShopView(@RequestBody Map<String,Object> map) {
        List<Map<String,Object>> list = sysDeptService.qryShopView(map);
        return R.ok().put("data", list);
    }


    /**
     * 信息
     */
    @PostMapping("/info/{deptId}")
    @ApiOperation(value = "信息")
    @RequiresPermissions("generator:sysdept:info")
    public R info(@PathVariable("deptId") String deptId) {
        SysDeptEntity sysDept = sysDeptService.getById(deptId);
        sysDept.setUser(sysUserService.getById(sysDept.getCreateBy()));
        sysDept.setSysUser(sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("dept_id", deptId)));
        sysDept.setLeaderUser(sysUserService.getById(sysDept.getLeader()));
        return R.ok().put("sysDept", sysDept);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation(value = "保存")
    @RequiresPermissions("generator:sysdept:save")
    public R save(@RequestBody SysDeptEntity sysDept) {
        String deptId = AppUtils.getUUID();
        sysDept.setDeptId(deptId);
        sysDept.setCreateBy(getUserId().toString());
        sysDept.setCreateTime(new Date());
        sysDept.setDelFlag(Constant.YES_OR_NO.YES.getValue());
        sysDeptService.insertDept(sysDept);
        SysUserEntity sysUser = sysDept.getSysUser();
        List<Long> roleId = new ArrayList<>();
        roleId.add(4l);
        sysUser.setRoleIdList(roleId);
        sysUser.setDeptId(deptId);
        //sysUser.setPassword(MD5Util.encrypt(sysUser.getPassword()));
        sysUserService.saveUser(sysUser);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    @RequiresPermissions("generator:sysdept:update")
    public R update(@RequestBody SysDeptEntity sysDept) {
        sysDept.setUpdateBy(getUserId().toString());
        sysDept.setUpdateTime(new Date());
        sysDeptService.updateDept(sysDept);
        SysUserEntity sysUser = sysDept.getSysUser();
        sysUserService.updateById(sysUser);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    @RequiresPermissions("generator:sysdept:delete")
    public R delete(@RequestBody String[] deptIds) {
        for (int i = 0;i < deptIds.length; i++){
            SysUserEntity sysUser = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("dept_id", deptIds[i]));
            if(sysUser != null){
                sysUserService.removeById(sysUser.getUserId());
                sysUserRoleService.removeByIds(sysUserRoleService.queryRoleIdList(sysUser.getUserId()));
            }
        }
        sysDeptService.removeByIds(Arrays.asList(deptIds));

        return R.ok();
    }

    /**
     * 查询部门列表
     *
     * @param sysDept
     * @return
     */
    @PostMapping("/qryDeptList")
    @ApiOperation(value = "查询部门列表")
    public R qryDeptList(@RequestBody SysDeptEntity sysDept) {
        if (StringUtils.isBlank(sysDept.getTenantId())) {
            return R.error("缺失必传参数");
        }
        List<Map<String, Object>> list = sysDeptService.listMaps(new QueryWrapper<SysDeptEntity>().eq("tenant_id", sysDept.getTenantId()).orderByAsc("order_num"));
        return R.ok().put("list", list);
    }

    /**
     * 查询公司介绍
     *
     * @参数   deptId
     * @return
     */
    @PostMapping("/qryDeptIntroduce")
    @ApiOperation(value = "查询公司介绍")
    public R qryDeptIntroduce(@RequestBody Map<String,Object> map) {
        if (StringUtils.isBlank(map.get("deptId").toString())) {
            return R.error("缺失必传参数");
        }
        SysDeptEntity sysDept = sysDeptService.qryDeptIntroduce(map.get("deptId").toString());
        return R.ok().put("data", sysDept);
    }
}
